package store

import (
	"editor/constant"
	"fmt"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"sync"
)

var (
	dbOnce sync.Once
	db     *xorm.Engine
)

func dbInit(ctx *gin.Context) (err error) {
	dbOnce.Do(func() {
		c := constant.Config.Mysql
		dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local",
			c.User, c.Pass, c.Ip, c.Port, c.DbName, c.Charset)
		db, err = xorm.NewEngine("mysql", dsn)
		if err != nil {
			Errorf(ctx, err, "database init failed")
			return
		}
		err = db.Ping()
		if err != nil {
			Errorf(ctx, err, "database ping failed")
			return
		} else {
			Infof(ctx, "database ping success")
		}
	})

	return
}

func reloadDB(ctx *gin.Context) (err error) {
	_ = db.Close()
	c := constant.Config.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local",
		c.User, c.Pass, c.Ip, c.Port, c.DbName, c.Charset)
	db, err = xorm.NewEngine("mysql", dsn)
	if err != nil {
		Errorf(ctx, err, "database init failed")
		return
	}
	err = db.Ping()
	if err != nil {
		Errorf(ctx, err, "database ping failed")
		return
	} else {
		Infof(ctx, "database ping success")
	}

	return
}

func DB() *xorm.Engine {
	db.ShowSQL(constant.Config.Mysql.ShowSQL)
	return db
}
